package com.example.passport.mapper;

import com.example.common.dto.Pagination;
import com.example.passport.entity.Logging;
import com.example.passport.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface LoggingMapper {

    @Insert("INSERT INTO `logging`" +
            " (`user_id`,`ip`,`login_equipment`,`login_time`,`tenant_id`) VALUES" +
            " (#{userId},  #{ip}, #{loginEquipment}, #{loginTime},#{tenantId})")
    void create(Logging logging);

    @Select("<script>" +
            "SELECT * FROM `logging`" +
            "<where>" +
            "<if test='condition.userId!=null'> AND `user_id`=#{condition.userId}</if>" +
            "<if test='condition.status!=0'> AND `status`=#{condition.status} </if>" +
            " AND `status`!=" + User.STATUS_DELETE +
            " AND `tenant_id`=#{condition.tenantId}"+
            "</where>" +
            " ORDER BY `login_time` DESC LIMIT #{pagination.offset}, #{pagination.limit}" +
            "</script>")
    List<Logging> findAll(@Param("condition") Logging condition, @Param("pagination") Pagination pagination);

    @Select("<script>" +
            "SELECT * FROM `logging`" +
            "<where>" +
            "<if test='condition.userId!=null'> AND `user_id`=#{condition.userId}</if>" +
            "<if test='condition.status!=0'> AND `status`=#{condition.status} </if>" +
            " AND `status`!=" + User.STATUS_DELETE +
            " AND `tenant_id`=#{condition.tenantId}"+
            "</where>" +
            "</script>")
    List<Logging> findAllByUserId(@Param("condition") Logging condition);

    @Select("<script>" +
            "SELECT COUNT(*) FROM `logging`" +
            "<where>" +
            "<if test='condition.userId!=null'> AND `user_id`=#{condition.userId}</if>" +
            "<if test='condition.status!=0'> AND `status`=#{condition.status} </if>" +
            "  AND `status`!=" + User.STATUS_DELETE +
            " AND `tenant_id`=#{condition.tenantId}"+
            "</where>" +
            "</script>")
    long count(@Param("condition") Logging condition);


    @Update("UPDATE `logging` SET `status` ="+ User.STATUS_DELETE+
            " WHERE `id`=#{id} AND `status`!=" + User.STATUS_DELETE+
            " AND `tenant_id`=#{tenantId}")
    int deleteById(Long tenantId,long id);

    @Update("UPDATE `logging` SET `end_time` =NOW()"+
            " WHERE `id`=#{id} AND `status`!=" + User.STATUS_DELETE+
            " AND `tenant_id`=#{tenantId}")
    int update(Long tenantId,Long id);
}
